<?php
namespace App\Logics;

use App\Models\ProjectModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\ChannelModel;
use App\Models\CategoryModel;
use App\Models\GoodsModel;
use App\Models\ChannelCateGoodsModel;

//逻辑处理
class ChannelLogic extends BaseLogic {


    public function __construct()
    {
        parent::__construct();

    }

    public  function index(array $para){
        $page =  isset($para['page'])?$para['page']:1;
        $per_page = isset($para['per_page'])?$para['per_page']:20;
        $cha_name = isset($para['cha_name'])?$para['cha_name']:'';
        $cha_id = isset($para['cha_id'])?$para['cha_id']:0;
        $cha_status = isset($para['cha_status'])?$para['cha_status']:-1;

        $where = $searchWhere = [];

        if ($cha_id > 0) {
            $where['cha_id'] = $cha_id;
            $searchWhere[] = ['cha_id', $cha_id];
        }
        if ($cha_status!=-1) {
            $where['cha_status'] = $cha_status;
            $searchWhere[] = ['cha_status', $cha_status];
        }
        if ($cha_name) {
            $where['cha_name'] = $cha_name;
            $searchWhere[] = ['cha_name', 'like', $cha_name . '%'];
        }
        if ($per_page != 20) {
            $where['per_page'] = $per_page;
        }



        $model = ChannelModel::where($searchWhere);
        $data = $model->paginate($per_page, ['*'], 'page', $page);
        $data = ob_to_array($data);
        $data['page_list'] = $this->page($data['last_page'], $data['current_page']);
        $data['up_page'] = ($data['current_page'] - 1) > 0 ? $data['current_page'] - 1 : 1;
        $data['next_page'] = ($data['current_page'] + 1) > $data['last_page'] ? $data['last_page'] : $data['current_page'] + 1;
        $url = url()->current() . '?&';
        foreach ($where as $k => $v) {
            $url .= "$k=$v&";
        }
        $data['page_url'] = trim($url, '&');

        $url=config('sys.img_url').'/';
        $project=ProjectModel::pluck('pro_name','pro_id');
        $arr=[
            'data'=>$data,
            'where'=>$where,
            'url'=>$url,
            'project'=>$project
        ];
        return $arr;
    }

    public   function add(array $para,Request $request){
        $cha_name= isset($para['cha_name'])?$para['cha_name']:'';
        $cha_describe=isset($para['cha_describe'])?$para['cha_describe']:'';
        $app_id=isset($para['app_id'])?$para['app_id']:'';
        $is_typ=isset($para['is_typ'])?$para['is_typ']:1;
        $is_typ=$is_typ==1?1:2;

        if(empty($cha_name)){
            return error('请填写渠道名称');
        }

        if(empty($cha_describe)){
            return error('请填写渠道描述');
        }
        if(empty($app_id)){
            return error('请填写渠道app_id');
        }

        $logo='';
        if($request->hasFile('img')){
            $data=$this->uploadImg($request,'img','brand');
            if($data['status']==0) return json_error($data['data']);
            $logo=$data['data'];
        }
        $data=[
            'cha_name'=>$cha_name,
            'cha_describe'=>$cha_describe,
            'app_id'=>$app_id,
            'is_typ'=>$is_typ,
            'cha_creat_time'=>date('Y-m-d H:i:s'),
            'logo'=>$logo
        ];
        $res=ChannelModel::insert($data);
        if($res){
            return success('添加成功');
        }
        if($logo) $this->deleteImg($logo);
        return error('添加失败');
    }

    public function edit(array $para,Request $request){
        $cha_name= isset($para['cha_name'])?$para['cha_name']:'';
        $cha_describe=isset($para['cha_describe'])?$para['cha_describe']:'';
        $app_id=isset($para['app_id'])?$para['app_id']:'';
        $is_typ=isset($para['is_typ'])?$para['is_typ']:1;
        $cha_id= isset($para['cha_id'])?$para['cha_id']:0;
        $cha_status= isset($para['cha_status'])?$para['cha_status']:0;
        $is_typ=$is_typ==1?1:2;

        $channel=ChannelLogic::getOne($cha_id,['logo']);
        if(empty($channel))  return error('参数错误');
        if(!in_array($cha_status,[1,2,3,4])) return error('参数错误');

        if(empty($cha_name)){
            return error('请填写渠道名称');
        }
        if(empty($cha_describe)){
            return error('请填写渠道描述');
        }
        if(empty($app_id)){
            return error('请填写渠道app_id');
        }

        $logo='';
        if($request->hasFile('img')){
            $data=$this->uploadImg($request,'img','brand');
            if($data['status']==0) return error($data['data']);
            $logo=$data['data'];
        }
        $data=[
            'cha_name'=>$cha_name,
            'cha_describe'=>$cha_describe,
            'app_id'=>$app_id,
            'is_typ'=>$is_typ,
            'cha_upd_time'=>date('Y-m-d H:i:s'),
            'cha_status'=>$cha_status,
        ];
        if($logo) $data['logo']=$logo;
        $res= ChannelModel::where('cha_id',$cha_id)->update($data);
        if($res){
            if($logo && $channel['logo']) $this->deleteImg($channel['logo']);
            return success('编辑成功');
        }
        if($logo) $this->deleteImg($logo);
        return error('编辑失败');
    }

    public  function delImg(int $cha_id){
        $channel=ChannelModel::where('cha_id',$cha_id)->first();
        if(empty($channel)) return error('参数错误');
        $channel=ob_to_array($channel);
        ChannelModel::where('cha_id',$cha_id)->update(['logo'=>'']);
        if($channel['logo']) $this->deleteImg($channel['logo']);
        return success('删除成功');
    }

    public static function ajaxFieldsEdit(int $cha_id){
        $channel= ChannelLogic::getOne($cha_id,['is_typ']);
        if(empty($channel)) return error('参数错误');
        $res='';
        $zhi=0;
        $color='red';

        $is_typ=$channel['is_typ']==1?2:1;
        $zhi=$is_typ;
        $color=$zhi==2?'blue':'red';
        $res=ChannelModel::where('cha_id',$cha_id)->update(['is_typ'=>$is_typ]);
        if($res) return success('ok',['zhi'=>$zhi,'color'=>$color]);
        return error('编辑失败');
    }

    public function editCategory(array $para,Request $request){
        $cate_name= isset($para['cate_name'])?$para['cate_name']:'';
        $cate_note=isset($para['cate_note'])?$para['cate_note']:'';
        $cate_code=isset($para['cate_code'])?$para['cate_code']:'';
        $cate_code_name=isset($para['cate_code_name'])?$para['cate_code_name']:'';
        $cate_hot_search=isset($para['cate_hot_search'])?$para['cate_hot_search']:'';
        $pid=isset($para['pid'])?$para['pid']:0;
        $cate_id=isset($para['cate_id'])?$para['cate_id']:0;
        $p_sort=isset($para['p_sort'])?$para['p_sort']:20;
        $is_del=isset($para['is_del'])?$para['is_del']:0;
        $is_hidden=isset($para['is_hidden'])?$para['is_hidden']:2;

        $cate=CategoryModel::where('cate_id',$cate_id)->first();
        if(empty($cate)) return error('参数有误');
        $cate=ob_to_array($cate);
        $cha_id=$cate['cha_id'];
        if($cha_id>0){
            $num=ChannelModel::where('cha_id',$cha_id)->count();
            if($num==0) return error('分类的渠道不存在');
        }
        if($pid>0){
            $res=CategoryModel::where('cate_id',$pid)->first();
            $res=ob_to_array($res);
            if(empty($res)) return error('该上级分类不存在');
            if($res['cha_id'] !=$cha_id) return error('上级分类与渠道不对应');
            $childCate=CategoryLogic::getAllChild($cha_id,$cate_id);
            if(in_array($pid,$childCate)) return error('上级分类不能是自己或自己的子类');
        }
        if(empty($cate_name)){
            return error('请填写分类名称');
        }
        if(empty($cate_code)){
            return error('请填写类目码');
        }
        if(empty($cate_code_name)){
            return error('请填写类目码名称');
        }
        $cate_pic='';
        if($request->hasFile('img')){
            $data=$this->uploadImg($request,'img','category');
            if($data['status']==0) return json_error($data['data']);
            $cate_pic=$data['data'];
        }
        $is_del=$is_del==1?1:0;
        $is_hidden=$is_hidden==1?1:2;
        $data=[
            'cate_name'=>$cate_name,
            'cate_code'=>$cate_code,
            'cate_code_name'=>$cate_code_name,
            'cate_hot_search'=>$cate_hot_search,
            'cate_note'=>$cate_note,
            'pid'=>$pid,
            'p_sort'=>$p_sort,
            'is_del'=>$is_del,
            'is_hidden'=>$is_hidden
        ];
        if($cate_pic) $data['cate_pic']=$cate_pic;
        $res= CategoryModel::where('cate_id',$cate_id)->update($data);
        if($res){
            if($cate_pic && $cate['cate_pic']) $this->deleteImg($cate['cate_pic']);
            return success('编辑成功');
        }
        if($cate_pic) $this->deleteImg($cate_pic);
        return error('编辑失败');
    }

    public function addCategory(array $para,Request $request){
        $cate_name= isset($para['cate_name'])?$para['cate_name']:'';
        $cate_note=isset($para['cate_note'])?$para['cate_note']:'';
        $cate_code=isset($para['cate_code'])?$para['cate_code']:'';
        $cate_code_name=isset($para['cate_code_name'])?$para['cate_code_name']:'';
        $cate_hot_search=isset($para['cate_hot_search'])?$para['cate_hot_search']:'';
        $pid=isset($para['pid'])?$para['pid']:0;
        $cha_id=isset($para['cha_id'])?$para['cha_id']:0;

        $res=ChannelModel::where('cha_id',$cha_id)->count();
        if(empty($res)) return error('渠道不存在');

        if($pid>0 ){
            $res=CategoryModel::where('cate_id',$pid)->first();
            $res=ob_to_array($res);
            if(empty($res)) return error('该上级分类不存在');
            if($res['cha_id'] !=$cha_id) return error('上级分类与渠道不对应');
        }
        if(empty($cate_name)){
            return error('请填写分类名称');
        }
        if(empty($cate_code)){
            return error('请填写类目码');
        }
        if(empty($cate_code_name)){
            return error('请填写类目码名称');
        }
        $cate_pic='';
        if($request->hasFile('img')){
            $data=$this->uploadImg($request,'img','category');
            if($data['status']==0) return error($data['data']);
            $cate_pic=$data['data'];
        }
        $data=[
            'cha_id'=>$cha_id,
            'cate_name'=>$cate_name,
            'cate_code'=>$cate_code,
            'cate_code_name'=>$cate_code_name,
            'cate_pic'=>$cate_pic,
            'cate_hot_search'=>$cate_hot_search,
            'cate_note'=>$cate_note,
            'pid'=>$pid
        ];
        $res=CategoryModel::insert($data);
        if($res){
            return success('添加成功');
        }
        if($data['cate_pic']) $this->deleteImg($data['cate_pic']);
        return error('添加失败');
    }

    public   function goods(array $para){
        $cha_id= isset($para['cha_id'])?$para['cha_id']:0;
        $page = isset($para['page'])?$para['page']:1;
        $per_page = isset($para['per_page'])?$para['per_page']:20;
        $goods_name = isset($para['goods_name'])?$para['goods_name']:'';
        $goods_id = isset($para['goods_id'])?$para['goods_id']:0;
        $is_putaway = isset($para['is_putaway'])?$para['is_putaway']:-1;

        $where = $searchWhere = [];
        if($cha_id){
            $searchWhere[]=['c.cha_id',$cha_id];
            $where['cha_id']=$cha_id;
        }
        if ($per_page != 20) {
            $where['per_page'] = $per_page;
        }
        if ($goods_id > 0) {
            $where['goods_id'] = $goods_id;
            $searchWhere[] = ['goods.goods_id', $goods_id];
        }
        if ($goods_name) {
            $where['goods_name'] = $goods_name;
            $searchWhere[] = ['goods.goods_name', 'like', $goods_name . '%'];
        }
        if ($is_putaway != -1) {
            $where['is_putaway'] = $is_putaway;
            $searchWhere[] = ['goods.is_putaway', $is_putaway];
        }

//        p($searchWhere);die;

        $fields=['c.cha_cate_name','goods.keyword','goods.is_putaway','goods.goods_id','c.middle_id','c.cha_id','c.sort','goods.goods_name','goods.goods_price','goods.goods_official_price'];
        $model=GoodsModel::join('channel_cate_goods as c','goods.goods_id','=','c.goods_id')
            ->select($fields)->where($searchWhere);

        $data = $model->paginate($per_page, ['*'], 'page', $page);
        $data=ob_to_array($data);
        $is_putaway = config('sys.goods_status');
        foreach ($data['data'] as $k => $v) {
            $data['data'][$k]['goods_status'] = isset($is_putaway[$v['is_putaway']]) ? $is_putaway[$v['is_putaway']] : '未知状态';
        }

        $data['page_list'] = $this->page($data['last_page'], $data['current_page']);
        $data['up_page'] = ($data['current_page'] - 1) > 0 ? $data['current_page'] - 1 : 1;
        $data['next_page'] = ($data['current_page'] + 1) > $data['last_page'] ? $data['last_page'] : $data['current_page'] + 1;
        $url = url()->current() . '?&';
        foreach ($where as $k => $v) {
            $url .= "$k=$v&";
        }
        $data['page_url'] = trim($url, '&');

        if(isset($where['cha_id']))unset($where['cha_id']);
        $data=[
            'data'=>$data,
            'where'=>$where
        ];
        return $data;
    }

    public static function goodsDelete($id){
        if(empty($id)) return error('参数错误');
        $id_ar=explode(',',$id);
        $id_ar=array_map(function($v){
            return (int)$v;
        },$id_ar);
        $res= ChannelCateGoodsModel::whereIn('middle_id',$id_ar)->delete();
        if($res) return success('删除成功');

        return error('删除失败');
    }

    public  function getEditCategory(int $id){
        $data=CategoryModel::where('cate_id',$id)->first();
        if(empty($data)) return error('参数有误');
        $data=ob_to_array($data);
        $cha_id=(int)$data['cha_id'];
        $res=ChannelModel::select("cha_id")->where('cha_id',$cha_id)->first();
        if(empty($res)) return error('渠道不存在');
        $list= CategoryModel::where('cha_id',$cha_id)->get();
        $list=ob_to_array($list);
        $pid_ar=array_unique(array_column($list,'pid'));
        foreach($list as $k=>$v){
            if(in_array($v['cate_id'],$pid_ar)){
                $list[$k]['is_son']=0;
            }else{
                $list[$k]['is_son']=1;
            }
        }
        $list=$this->tree($list);

        $url=config('sys.img_url').'/';
        $data['cate_pic']=$data['cate_pic']?$url.$data['cate_pic']:$data['cate_pic'];

        $func_name= $this->getChannelController();
        $funcName=$func_name[$cha_id];
        return [
            'data'=>$data,
            'list'=>$list,
            'funcName'=>$funcName
        ];

    }

    private function getChannelController(){
         return [
            '1'=>'xcxCategory',
            '3'=>'jdH5Category',
            '4'=>'xcxDlCategory',
            '5'=>'xcxStCategory',
            '6'=>'xcxAbsCategory',
            '7'=>'xcxAblCategory',
            '8'=>'hbH5Category'
        ];
    }

    private function getChannelControllerName(){
        return [
            '1'=>'八戒租-分类列表',
            '3'=>'京东h5-分类列表',
            '4'=>'德龙分-类列表',
            '5'=>'舒坦分-类列表',
            '6'=>'艾泊斯-分类列表',
            '7'=>'爱宝乐-分类列表',
            '8'=>'花呗h5-分类列表',
        ];
    }

    public function category(int $cha_id){
        $cha_id=(int)$cha_id;

        $where = $searchWhere = [];
        if ($cha_id > 0) {
            $where['cha_id'] = $cha_id;
            $searchWhere[] = ['cha_id', $cha_id];

        }
        $list=CategoryModel::where($searchWhere)->get();
        $list=ob_to_array($list);


        $url=config('sys.img_url').'/';
        $pid_ar=array_unique(array_column($list,'pid'));

        foreach($list as $k=>$v){
            $list[$k]['cate_pic']=$v['cate_pic']?$url.$v['cate_pic']:$v['cate_pic'];
            if(in_array($v['cate_id'],$pid_ar)){
                $list[$k]['is_son']=0;
            }else{
                $list[$k]['is_son']=1;
            }

        }
        $list=$this->tree($list);
        $channel =ChannelModel::pluck('cha_describe', 'cha_id');
        $channel=ob_to_array($channel);

        $lists=[];
        foreach($list as $k=>$v){
            $list[$k]['cha_name']=isset($channel[$v['cha_id']])?$channel[$v['cha_id']]:($v['cha_id']==0?'平台':'未知渠道');
            if($v['pid']==0){
                $lists[]=$list[$k];
            }
        }

        $name_ar= $this->getChannelControllerName();
        $listName=$name_ar[$cha_id];
        $data=[
            'list'=>$lists,
            'channel'=>$channel,
            'where'=>$where,
            'cha_id'=>$cha_id,
            'listName'=>$listName
        ];

       return $data;
    }

    public function getAddCategory(int $cha_id){
        $res= ChannelModel::select("cha_id")->where('cha_id',$cha_id)->first();
        if(empty($res)) return error('渠道不存在');
        if(!in_array($cha_id,[1,3,4,5,6,7,8])) return error('不合法渠道');
        $list= CategoryModel::where('cha_id',$cha_id)->get();
        $list=ob_to_array($list);
        $pid_ar=array_unique(array_column($list,'pid'));
        foreach($list as $k=>$v){
            if(in_array($v['cate_id'],$pid_ar)){
                $list[$k]['is_son']=0;
            }else{
                $list[$k]['is_son']=1;
            }
        }
        $list=$this->tree($list);

        $func_name= $this->getChannelController();
        $funcName=$func_name[$cha_id];
        return [
            'list'=>$list,
            'funcName'=>$funcName,
            'cha_id'=>$cha_id
        ];
    }

    public static function editSort(int $id,int $sort){
        if($sort<1) $sort=20;
        $res=ChannelCateGoodsModel::where('middle_id',$id)->update(['sort'=>$sort]);
        if($res) return success('ok');
        return error('修改失败');
    }

    //获取一个
    public static function  getOne($cha_id,$fields=['*']){
        $cha_id=(int)$cha_id;
        $data= ChannelModel::where('cha_id',$cha_id)->select($fields)->first();
        return ob_to_array($data);
    }


    //判断该数据是否存在
    public static function isOne($cha_id){
        $cha_id=(int)$cha_id;

        return ChannelModel::where('cha_id',$cha_id)->count();
    }

    public static function pluck(string $name,$key=null,array $where=[]){
        return  ChannelModel::where($where)->pluck($name,$key)->toArray();
    }

    public function  getCategoryLevel(int $id){
        static $level=0;
        $cate=CategoryModel::where('cate_id',$id)->select('pid')->first();
        if($cate){
            $cate=ob_to_array($cate);
            if($cate['pid']>0){
                $level+=1;
                $this->getCategoryLevel($cate['pid']);
            }
        }
        return $level;
    }

    public function getLevelStr(int $level){
        $str="|&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
        $level_str='';
        for($i=0;$i<$level;$i++){
            $level_str.=$str;
        }
        return $level_str;
    }

    public function getChildHtml(int $id){
        $cate=CategoryModel::where('cate_id',$id)->select('cha_id')->first();

        if(empty($cate)) return '';
        $cate=ob_to_array($cate);
        $cha_id=(int)$cate['cha_id'];

        $data=CategoryModel::where('pid',$id)->get();
        $data=ob_to_array($data);

        $pid_ar=CategoryModel::where('cha_id',$cha_id)->pluck('pid');
        $pid_ar=ob_to_array($pid_ar);

        if($data){
            $channel =ChannelModel::pluck('cha_describe', 'cha_id');
            $channel=ob_to_array( $channel);
            $level=$this->getCategoryLevel($data[0]['cate_id']);
            $level_str=$this->getLevelStr($level);
            $url=config('sys.img_url').'/';
            foreach($data as $k=>$v){
                $data[$k]['cate_pic']=$url.$v['cate_pic'];
                $data[$k]['level']=$level;
                $data[$k]['level_str']=$level_str;
                $data[$k]['cha_name']=isset($channel[$v['cha_id']])?$channel[$v['cha_id']]:($v['cha_id']==0?'平台':'未知渠道');
                if(in_array($v['cate_id'],$pid_ar)){
                    $data[$k]['is_son']=0;
                }else{
                    $data[$k]['is_son']=1;
                }
            }
        }





        $html='';
        foreach($data as $v){
            $html.="<tr id='tr".$v['cate_id']."'  class='trpid".$v['pid']."'  >
                                            <td >".$v['cate_id']."  </td>
                                            <td >".$v['level_str'].$v['cate_name']." </td>
                                            <td >".$v['cate_code']."</td>";


            $html.="<td ><img width='100' src='".$v['cate_pic']."'   ></td>";
            if($v['is_del']==0){
                $html.="<td><span   style='color:blue;'>否</span></td>";
            }else{
                $html.="<td><span   style='color:red;'>是</span></td>";
            }
            if($v['is_hidden']==1){
                $html.="<td><span   style='color:blue;'>否</span></td>";
            }else{
                $html.="<td><span   style='color:red;'>是</span></td>";
            }
            $html.="<td>".$v['cha_name']."</td><td>".$v['level']."</td>";

            if($v['is_son']==0){
                $html.="<td> <span onclick='showChild(".$v['cate_id'].")' class='showChild' style='border - radius:5px;padding:5px;background:#00a7d0;color:#f9f9f9' data-id='".$v['cate_id']."' >查看子分类</span></td>";
            }else{
                $html.="<td> <span   class='showChild' style='border-radius:5px;padding:5px;background:#00a7d0;color:red;' data-id='".$v['cate_id']."' >无子类</span></td>";
            }
            $html.="<td><a href='/admin/channel/editCategory?id=".$v['cate_id']."'>编辑</a></td>";
            $html.="</tr>";
        }

        return $html;
    }





}
